<?php

abstract class Kd_Html_Grid_Head_Base extends Kd_Html_Element {

    private $_column = NULL;
    private $_align = NULL;

    public function __construct() {
        parent::__construct();
    }

    public function getAlign() {
        if (is_null($this->_align)) {
            return $this->getColumn()->getAlign();
        }
        return $this->_align;
    }

    public function setAlign($value) {
        $this->_align = $value;
        return $this;
    }

    public function setColumn($value) {
        $this->_column = $value;
        return $this;
    }

    public function getColumn() {
        return $this->_column;
    }

    public function getGrid() {
        return $this->getColumn()->getGrid();
    }

    protected function getSortUrl() {
        if ($this->getGrid()->getSortField() == $this->getColumn()->getSortField()) {
            $direction = $this->getGrid()->getSortDirection() == 'asc' ? 'desc' : 'asc';
        } else {
            $direction = 'asc';
        }
        $result = str_replace('{field}', $this->getColumn()->getSortField(), $this->getGrid()->getSortUrlFormat());
        return str_replace('{direction}', $direction, $result);
    }

    public function getAttributeHtml() {
        if ($this->getColumn()->getName()) {
            $this->addClass($this->getColumn()->getName());
        }
        if ($this->getColumn()->getSortField()) {
            $this->addClass('sort');
            if ($this->getGrid()->getSortField() == $this->getColumn()->getSortField()) {
                $this->addClass($this->getGrid()->getSortDirection());
            }
        }

        return parent::getAttributeHtml();
    }

    public function toHtml() {
        $tmpl = $this->getTemplate();
        if (!empty($tmpl)) {
            ob_start();
            include $tmpl;
            return ob_get_clean();
        } else {
            $customRender = $this->getGrid()->getHeadRender();
            if ($customRender) {
                $functionName = $customRender['function'];
                $functionArgs = array_unshift($customRender['args'], $this);
                $result = call_user_func_array($functionName, $functionArgs);
                if ($result === FALSE) {
                    return $this->render();
                }
                return $result;
            }
            return $this->render();
        }
    }

}